package ngat.oss;

import ngat.net.*;
import ngat.util.*;

public class TransactionQueue {

    protected static PriorityQueueBuffer queue;

    protected static BooleanLock block;

    /** Initialize the Queue with specified no. of levels.*/
    public static void init(int numPriorityLevels) {
	queue = new PriorityQueueBuffer(numPriorityLevels);
	block = new BooleanLock(true);
    }

    /** Attaches the named connection thread to the queue at specified level.*/
    public static void attach(int level, BlockableThread bt) throws InterruptedException {
	queue.add(level, bt);
    }

    /** Retrieves the next (highest level) connection thread from the queue.
     * Will wiat effectively forever or until interrupted
     * @exception InterruptedException If any thread interrupts while waiting. */
    public static BlockableThread next() throws InterruptedException, QueueEmptyException {
	return (BlockableThread)queue.remove();
    }
   
    /** Reader should call this to block waiting for release.*/
    public static void readerWait() throws InterruptedException {
	System.err.println("TQ::ReaderWait - START");
	block.waitUntilTrue(0L);
	System.err.println("TQ::ReaderWait - DONE");
    }
    
    /** Writers should call this to release the reader when they are done or failed.*/
    public static void readerRelease() {
	block.setValue(true);
	System.err.println("TQ::ReaderRelease");
    }
    
    /** Reader should call this to reset the lock.*/
    public static void readerBlock() {
	block.setValue(false);
	System.err.println("TQ::ReaderBlock");
    }
}
